﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
//using System.Windows.Shapes;
using MahApps.Metro.Controls;
using MahApps.Metro.Controls.Dialogs;
using ControlzEx.Theming;
using System.Diagnostics;
using System.Threading;
using System.IO;
using System.Threading.Tasks;

namespace WpfBeyond
{
    /// <summary>
    /// WindowPlayList.xaml 的交互逻辑
    /// </summary>
    public partial class WindowPlayList : MetroWindow
    {
        private List<PlayInfo> playlist = new List<PlayInfo>();

        public WindowPlayList(List<PlayInfo> list)
        {
            InitializeComponent();

            playlist = list;
            grid_playlist.ItemsSource = playlist;
        }

        private void btn_ok_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = true;
        }

        private async void btn_add_Click(object sender, RoutedEventArgs e)
        {
            double value = 0;
            Microsoft.Win32.OpenFileDialog op = new Microsoft.Win32.OpenFileDialog();
            op.Multiselect = true;
            if (op.ShowDialog() == true)
            {
                var controller = await this.ShowProgressAsync("分析音频文件中...", "请稍后");

                controller.Maximum = op.FileNames.Length;
                Process pro = new Process();
                StringBuilder sb = new StringBuilder();

                foreach (string fileName in op.FileNames)
                {
                    PlayInfo p = new PlayInfo();
                    if (playlist.Count == 0)
                    {
                        p.Id = 1;
                    }
                    else
                    {
                        p.Id = playlist[playlist.Count - 1].Id + 1;
                    }

                    value++;
                    controller.SetProgress(value);
                    if (sb.Length > 150)
                    {
                        sb.Remove(0, sb.ToString().IndexOf("\r\n") + 2);
                    }
                    sb.Append("载入音频文件:" + fileName + "\r\n");
                    controller.SetMessage(sb.ToString());

                    //委托刷新进度条
                    this.Dispatcher.Invoke(new Action<double>(controller.SetProgress), System.Windows.Threading.DispatcherPriority.Background, value);

                    pro.StartInfo.UseShellExecute = false;
                    pro.StartInfo.ErrorDialog = false;
                    pro.StartInfo.CreateNoWindow = true;
                    pro.StartInfo.RedirectStandardError = true;
                    pro.StartInfo.FileName = @"ffmpeg.exe";

                    pro.StartInfo.Arguments = " -i \"" + fileName + "\"";
                    pro.Start();
                    System.IO.StreamReader reader = pro.StandardError;
                    pro.WaitForExit(1000);
                    string result = reader.ReadToEnd();
                    string duration = "00:00:00";
                    string audioinfo = "";
                    if (!string.IsNullOrEmpty(result))
                    {
                        //Duration: 00:04:31.54, start: 0.025057, bitrate: 128 kb/s                        
                        duration = result.Substring(result.IndexOf("Duration: ") + ("Duration: ").Length, ("00:00:00").Length);

                        try
                        {
                            TimeSpan.Parse(duration);
                            p.Duration = duration;
                        }
                        catch
                        {
                            p.Duration = duration;
                        }

                        //Stream #0:0: Audio: mp3, 32000 Hz, stereo, fltp, 192 kb/s
                        audioinfo = result.Substring(result.IndexOf("Audio: ") + ("Audio: ").Length);
                        audioinfo = audioinfo.Substring(0, audioinfo.IndexOf("\r\n"));
                        string[] audioinfos = audioinfo.Split(",");
                        if (audioinfos.Length > 1)
                        {
                            p.Sample_rate = audioinfos[1];
                        }
                    }

                    p.FileName = System.IO.Path.GetFileName(fileName);
                    p.FilePath = fileName;

                    playlist.Add(p);
                }

                await Task.Delay(500);
                await controller.CloseAsync();

            }

            grid_playlist.ItemsSource = null;
            grid_playlist.ItemsSource = playlist;
        }

        private void DelClick(object sender, RoutedEventArgs e)
        {
            Button btn = sender as Button;

            if (btn.Tag == null) return;

            int id = int.Parse(btn.Tag.ToString());

            foreach (PlayInfo p in playlist)
            {
                if (id == p.Id)
                {
                    playlist.Remove(p);
                    grid_playlist.ItemsSource = null;
                    grid_playlist.ItemsSource = playlist;
                    return;
                }
            }

        }

        private void btn_clear_Click(object sender, RoutedEventArgs e)
        {
            playlist.Clear();
            grid_playlist.ItemsSource = null;
            grid_playlist.ItemsSource = playlist;
        }

        private void btn_Convert_Click(object sender, RoutedEventArgs e)
        {
            foreach (PlayInfo p in playlist)
            {
                if (p.Sample_rate.Trim() == "44100 Hz") continue;

                Process pro = new Process();

                pro.StartInfo.UseShellExecute = false;
                pro.StartInfo.ErrorDialog = false;
                pro.StartInfo.CreateNoWindow = true;
                pro.StartInfo.RedirectStandardError = true;
                pro.StartInfo.FileName = @"ffmpeg.exe";

                pro.StartInfo.Arguments = " -i \"" + p.FilePath + "\" -acodec mp3 -ar 44100 " + p.FileName;
                pro.Start();
                System.IO.StreamReader reader = pro.StandardError;
                pro.WaitForExit(1000);
                string result = reader.ReadToEnd();

                //size = 264kB time = 00:00:16.87 bitrate = 128.3kbits / s speed = 88.8x
                //video:0kB audio:264kB subtitle:0kB other streams: 0kB global headers: 0kB muxing overhead: 0.113528 %

                if (!string.IsNullOrEmpty(result))
                {
                    p.FilePath = p.FileName;
                    p.Sample_rate = " 44100 Hz";
                }
            }
            grid_playlist.ItemsSource = null;
            grid_playlist.ItemsSource = playlist;
        }
    }
}
